﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace Kokomo
{
	public class EventBindingManager : DependencyObject
	{
		public static EventBindingCollection GetEventBindings(DependencyObject obj)
		{
			return (EventBindingCollection)obj.GetValue(EventBindingsProperty);
		}

		public static void SetEventBindings(DependencyObject obj, EventBindingCollection value)
		{
			obj.SetValue(EventBindingsProperty, value);
		}

		// Using a DependencyProperty as the backing store for EventBindings.  This enables animation, styling, binding, etc...
		public static readonly DependencyProperty EventBindingsProperty =
			DependencyProperty.RegisterAttached("EventBindings", typeof(EventBindingCollection), typeof(EventBindingManager), new UIPropertyMetadata(null, OnEventBindingsChanged));

		private static void OnEventBindingsChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
		{
			EventBindingCollection oldCollection = (EventBindingCollection)e.OldValue;
			if (oldCollection != null)
			{
				foreach (var eventBinding in oldCollection)
				{
					eventBinding.Detach(target);
				}
			}
			EventBindingCollection newCollection = (EventBindingCollection)e.NewValue;
			if (newCollection != null)
			{
				foreach (var eventBinding in newCollection)
				{
					eventBinding.Attach(target);
				}
			}
		}
	}
}
